//
//  AddressGroupVC.m
//  ChangChat
//
//  Created by Cocoa on 2019/9/12.
//  Copyright © 2019 yibai. All rights reserved.
//

#import "AddressGroupVC.h"
#import "FriendCell.h"
#import "Address_groupItem.h"
#import "FriendInfoListVC.h"
#import "EVCPopInputView.h"
#import "YBApiManager+Friend.h"
#import "YCMenuView.h"
#import <LKDBHelper/LKDBHelper.h>

@interface AddressGroupVC ()

@property (nonatomic, strong) NSMutableArray *boolArr;

@end
@implementation AddressGroupVC


- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self setupDatasource];
    self.pContentView.type = 666;
    @weakify(self);
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:notification_Friend_groupList_updated object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification * _Nullable x) {
        @strongify(self);
        [self setupDatasource];
    }];
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:notification_Friend_Info_Changed object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification * _Nullable x) {
        @strongify(self);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            FriendItem *item = x.object;
            [self.tableView reloadData];
//            for (Address_groupItem *content in kUsermanager.friend_groupArray) {
//                for (FriendItem *friend  in content.friendArray) {
//                    if ([friend.friend_id isEqualToString:item.friend_id] == YES) {
//                        [self.tableView reloadData];
//                        break;
//                    }
//                }
//            }
        });
    }];
}
- (void)setupUI {
    [self.tableView customRegisterClassWithName:@"FriendCell"];
    UIButton *btn = UIButton.k_init().k_title(@"添加").k_font([UIFont systemFontOfSize:15]);
    btn.tintColor = UIColor.whiteColor;
    [btn addTarget:self action:@selector(didClickRightBarBtnItemAction) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *rightBarBtnItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    
    self.navigationItem.rightBarButtonItem = rightBarBtnItem;
}
- (void)setupDatasource {
    self.boolArr = [NSMutableArray array];
    for (int i = 0; i < kUsermanager.friend_groupArray.count; i++) {
        [self.boolArr addObject:@NO];
    }
    [self.tableView reloadData];
}

#pragma mark - tableview delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return kUsermanager.friend_groupArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([self.boolArr[section] boolValue] == NO) {
        
        return 0;
    }
    Address_groupItem *item = kUsermanager.friend_groupArray[section];
    return item.friendArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 50;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UITableViewHeaderFooterView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"headerView"];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"headerView"];
        
        
        headerView.backgroundColor = [UIColor colorWithRed:235/255.0 green:235/255.0 blue:235/255.0 alpha:1];
        
        //添加imageview
        UIImageView * iv = [[UIImageView alloc] initWithFrame:CGRectMake(10, 19, 12, 12)];
        
        //三目运算选择展开或者闭合时候的图标
        iv.image = [_boolArr[section] boolValue] ? [UIImage imageNamed:@"buddy_header_arrow_down"] : [UIImage imageNamed:@"buddy_header_arrow_right"];
        [headerView addSubview:iv];
        
        //添加标题label
        UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(35, 0, self.view.frame.size.width - 100, 50)];
        label.tag = 2019;
        [headerView addSubview:label];
        
        //添加分组人数和在线人数显示的label
        UILabel * labelR = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width-60, 0, 60, 50)];
        labelR.textAlignment = NSTextAlignmentCenter;
        labelR.tag = 2020;
        [headerView addSubview:labelR];
        
        //添加轻扣手势
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGR:)];
        [headerView addGestureRecognizer:tap];
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longpressGR:)];
        [headerView addGestureRecognizer:longPress];
//        UIButton *btn = UIButton.k_init();
//        [headerView addSubview:btn];
//        btn.frame = CGRectMake(0, 0, ScreenWidth, 50);
//        btn.tag = 2021;
    }
    headerView.tag = 3016 + section;
    
    Address_groupItem *item = kUsermanager.friend_groupArray[section];
    UILabel *label = (UILabel *)[headerView viewWithTag:2019];
    label.text = item.name;
    UILabel *right_label = (UILabel *)[headerView viewWithTag:2020];
    right_label.text = [NSString kk_stringWithInteger:item.friendArray.count];
    UIButton *btn = (UIButton *)[headerView viewWithTag:2021];
    @weakify(self);
    [[[btn rac_signalForControlEvents:UIControlEventTouchUpInside] takeUntil:headerView.rac_prepareForReuseSignal] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
        //判断改变bool值
        if ([self.boolArr[section] boolValue] == YES) {
            [self.boolArr replaceObjectAtIndex:section withObject:@NO];
        }else {
            [self.boolArr replaceObjectAtIndex:section withObject:@YES];
        }
        //刷新某个section
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationFade];
    }];
    
    return headerView;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    FriendCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FriendCell" forIndexPath:indexPath];
    Address_groupItem *model = kUsermanager.friend_groupArray[indexPath.section];
    FriendItem *friend = [model.friendArray objectAtIndex:indexPath.row];
    cell.friendItem = friend;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    Address_groupItem *model = kUsermanager.friend_groupArray[indexPath.section];
    FriendItem *friend = [model.friendArray objectAtIndex:indexPath.row];
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self showFriendInfoVCWithType:2 friendItem:friend from:@"0"];
}

- (void)showFriendInfoVCWithType:(NSInteger)type friendItem:(FriendItem *)item from:(NSString *)from {
    FriendInfoListVC *VC = [FriendInfoListVC new];
    VC.user = item;
    VC.from = from;
    VC.listType = type;
    
    [self.navigationController pushViewController:VC animated:YES];
}
- (void)didClickRightBarBtnItemAction {
    EVCPopInputView *popView = [EVCPopInputView popInputViewWithTitle:@"添加分组" subTitle:nil placehold:@"请输入分组名称" preset:nil];
    [popView show];
    [popView clickButtonAction:^(NSInteger index, NSString *content) {
        if (index == 1) {
            [self addNewGroupWithName:content];
        }
    }];
}
- (void)addNewGroupWithName:(NSString *)name {
    
    [MBProgressHUD showActivityMessageInView:@""];
    [[YBApiManager.shareManager addOrEditAddressGroupWithName:name sortID:@""] subscribeNext:^(id  _Nullable x) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showTipMessageInView:@"添加分组成功" timer:1.0f];
        NSDictionary *dataDic = [ x objectForKey:@"data"];
        Address_groupItem *item = [Address_groupItem mj_objectWithKeyValues:dataDic];
        [kUsermanager.friend_groupArray insertObject:item atIndex:kUsermanager.friend_groupArray.count-1];
        [self.boolArr insertObject:@NO atIndex:self.boolArr.count-1];
        [self.tableView reloadData];
    } error:^(NSError * _Nullable error) {
        [MBProgressHUD hideHUD];
        if ([error isServerError]) {
            [MBProgressHUD showTipMessageInView:error.localizedDescription timer:1.0f];
        } else {
            [MBProgressHUD showTipMessageInView:@"网络错误，请重试" timer:1.0f];
        }
    }];
}
- (void)tapGR:(UITapGestureRecognizer *)tap {
    NSInteger section = [tap.view tag] - 3016;
    if ([self.boolArr[section] boolValue] == YES) {
        [self.boolArr replaceObjectAtIndex:section withObject:@NO];
    }else {
        [self.boolArr replaceObjectAtIndex:section withObject:@YES];
    }
    //刷新某个section
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationFade];
}
- (void)longpressGR:(UILongPressGestureRecognizer *)longpress {
    
    if (longpress.state != UIGestureRecognizerStateBegan) {
        return;
    }
    NSInteger section = [longpress.view tag] - 3016;

    @weakify(self);
    YCMenuAction *action1 = [YCMenuAction actionWithTitle:@"重命名" image:UIImage.k_imgName(@"") handler:^(YCMenuAction *action) {
        @strongify(self);
        [self renameGroupWithSection:section];
    }];
//    action1.highlightImage = UIImage.k_imgName(@"new_add_highlight");
    YCMenuAction *action2 = [YCMenuAction actionWithTitle:@"删除" image:UIImage.k_imgName(@"") handler:^(YCMenuAction *action) {
        @strongify(self);
        [self deleteGroupWithSection:section];
    }];
//    action2.highlightImage = UIImage.k_imgName(@"new_qr_highlight");
    
    YCMenuView *view = [YCMenuView menuWithActions:@[action1, action2] width:135 relyonView:longpress.view];
    view.textColor = UIColor.k_t2Color;
    
    [view show];
}

- (void)renameGroupWithSection:(NSInteger)section {
    Address_groupItem *item = kUsermanager.friend_groupArray[section];
    @weakify(self);
    EVCPopInputView *popView = [EVCPopInputView popInputViewWithTitle:@"修改群名称" subTitle:nil placehold:@"请输入群组名称" preset:item.name];
    [popView show];
    [popView clickButtonAction:^(NSInteger index, NSString *content) {
        if (index == 1) {
            [MBProgressHUD showActivityMessageInView:@""];
            [[YBApiManager.shareManager addOrEditAddressGroupWithName:content sortID:item.sort_id] subscribeNext:^(id  _Nullable x) {
                [MBProgressHUD hideHUD];
                [MBProgressHUD showTipMessageInView:@"修改成功" timer:1.0f];
                item.name = content;
                @strongify(self);
                [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationNone];
            } error:^(NSError * _Nullable error) {
                [MBProgressHUD hideHUD];
                if ([error isServerError]) {
                    [MBProgressHUD showTipMessageInView:error.localizedDescription timer:1.0f];
                } else {
                    [MBProgressHUD showTipMessageInView:@"网络错误，请重试" timer:1.0f];
                }
            }];
        }
    }];
}
- (void)deleteGroupWithSection:(NSInteger)section {
    Address_groupItem *item = kUsermanager.friend_groupArray[section];

    [LBXAlertAction showAlertWithTitle:@"提示" msg:@"确定删除分组？" buttonsStatement:@[@"取消", @"确定"] chooseBlock:^(NSInteger buttonIdx) {
        
        if (buttonIdx == 1) {
            [MBProgressHUD showActivityMessageInView:@""];
            [[YBApiManager.shareManager deleteAddressGroupWithSortID:item.sort_id] subscribeNext:^(id  _Nullable x) {
                [MBProgressHUD hideHUD];
                [MBProgressHUD showTipMessageInView:@"删除成功" timer:1.0f];
                [Address_groupItem deleteWithWhere:@{@"sort_id": item.sort_id}];
                [kUsermanager.friend_groupArray removeObjectAtIndex:section];
                [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationAutomatic];
                [kUsermanager updateFriend_groupList];
                
            } error:^(NSError * _Nullable error) {
                [MBProgressHUD hideHUD];
                if ([error isServerError]) {
                    [MBProgressHUD showTipMessageInView:error.localizedDescription timer:1.0f];
                } else {
                    [MBProgressHUD showTipMessageInView:@"网络错误，请重试" timer:1.0f];
                }
            }];
        }
    }];
}


@end
